package com.opesoft.fw.edm.impl;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import uk.ltd.getahead.dwr.WebContext;

import com.opesoft.fw.core.Constants;
import com.opesoft.fw.core.utils.StrUtils;
import com.opesoft.fw.edm.Logic;
import com.opesoft.fw.edm.Respond;

public abstract class StandardLogic implements Logic
{
	protected WebContext webContext;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	protected Map data=new HashMap();
	Logger log=Logger.getLogger(this.getClass());

	public void init(WebContext webContext,String data) throws Exception
	{
		this.webContext=webContext;
		this.request=webContext.getHttpServletRequest();
		this.response=webContext.getHttpServletResponse();
		this.session=request.getSession();
		this.data=StrUtils.formData2Map(data);
	}

	public Object error(Exception e)
	{
		e.printStackTrace();
		
		Throwable t=e;
		while(t.getMessage()==null)
		{
			t=t.getCause();
		}
		return new Respond(false,"[Error] "+t.getMessage());
	}

	public Object extractForm(Object bean)
	{
		try
		{
			if(bean!=null&&this.data!=null) BeanUtils.populate(bean,this.data);
		}
		catch(Exception e)
		{
			log.error(e);
			if(Constants.MODE.equalsIgnoreCase("develop")) e.printStackTrace();
		}
		return bean;
	}

	public Object extractForm(Class clazz)
	{
		try
		{
			return this.extractForm(clazz.newInstance());
		}
		catch(InstantiationException e)
		{
			e.printStackTrace();
		}
		catch(IllegalAccessException e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
